import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {ValidateProvider} from "../../providers/validate/validate";
import {ConfigProvider} from "../../providers/config/config";
import {HttpServicesProvider} from "../../providers/http-services/http-services";
import {CommonProvider} from "../../providers/common/common";
import {StorageProvider} from "../../providers/storage/storage";

/// <reference path="../assets/libs/wxsdk/wechat.d.ts">

@IonicPage({
    segment: 'member/wallet/recharge',
    defaultHistory: ['MemberPage']
})
@Component({
    selector: 'page-money-recharge',
    templateUrl: 'money-recharge.html',
})
export class MoneyRechargePage {
    postData = {
        amount: '',
        openid: '',
        token: ''
    };

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public validate: ValidateProvider,
        public config: ConfigProvider,
        public httpService: HttpServicesProvider,
        public common: CommonProvider,
        public storage: StorageProvider
    ) {
        if (!this.validate.checkLogin()) {
            this.navCtrl.push('LoginPage');
        }
    }

    //判断用户是否登录
    ionViewCanEnter(){
        return this.validate.checkLogin();
    }

    ionViewWillEnter() {
        let token = this.config.getToken();
        let openid = this.config.getOpenid();
        this.postData = {
            openid: openid,
            amount: '',
            token: token
        };
        this.getWxConfig();
    }

    getWxConfig() {
        this.httpService.requestPostData('/wechat/get_wx_config', {
            url: location.href.split("#")[0]
        }, response => {
            let config = response['info'];
            wx.config({
                // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: config['appid'], // 必填，公众号的唯一标识
                timestamp: config['time'], // 必填，生成签名的时间戳
                nonceStr: config['noncestr'], // 必填，生成签名的随机串
                signature: config['signature'],// 必填，签名
                jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
            });
        });
    }

    doRecharge() {
        let _this = this;
        this.httpService.requestPostData('/echarge/recharge', this.postData, response => {
            let config = response['pay_code'];
            wx.chooseWXPay({
                timestamp: config['timeStamp'], // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                nonceStr: config['nonceStr'], // 支付签名随机串，不长于 32 位
                package: config['package'], // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                signType: config['signType'], // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                paySign: config['paySign'], // 支付签名
                success: function (res) {
                    localStorage.setItem('wxPaySuccessInfo', JSON.stringify(res));
                    if(_this.common.getBackPage()){
                        let backPage = _this.common.getBackPage();
                        _this.navCtrl.push(backPage['page'],backPage.params);
                    }else{
                        _this.navCtrl.push('MoneyRechargeResultPage');
                    }
                }
            });
        });
    }


    /**
     * 当离开页面时清除数据
     * */
    ionViewWillLeave(){
        this.storage.remove('backPage');
    }
}
